package com.podium.auth.utils;

import com.podium.auth.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author 邵文泽
 * @description 安全工具类
 * @date 2025/4/14 14:59
 */
public class SecurityUtils {

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息
     */
    public static LoginUser getLoginUser() {
        Authentication authentication = getAuthentication();
        return (LoginUser) authentication.getPrincipal();
    }


    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取用户名称
     */
    public static String getUsername() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取用户密码
     */
    public static String getPassword() {
        return getLoginUser().getPassword();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }


    public static void main(String[] args) {
        String password = encryptPassword("admin@1234");
        System.out.println("password = " + password);
    }

}
